using AvalonAdmin.Attributes;
using AvalonAdmin.BaseControl;
using AvalonAdmin.BaseViewModel;
using AvalonAdmin.Consts;
using AvalonAdmin.Helpers;
using AvalonAdmin.Models;
using AvalonAdmin.Pages.CarType.Views.CarTypeVersion;
using AvalonAdmin.Pages.Common.ViewModels;
using AvalonAdmin.Pages.Common.Views;
using AvalonAdminDto.Base;
using AvalonAdminDto.CarType.CarTypeVersionDtos;
using AvalonAdminDto.CarType.CountryDtos;
using AvalonAdminDto.Common;
using Avalonia;
using Avalonia.Platform.Storage;
using Avalonia.Threading;
using D.UtilCore.Dtos;
using D.UtilFreesqlOrm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Ursa.Controls;

namespace AvalonAdmin.Pages.CarType.ViewModels.CarTypeVersion
{
    /// <summary>
    /// 车型版本管理视图模型
    /// </summary>
    [PagePath("CarType.Views.CarTypeVersion.Page_CarTypeVersion")]
    public class CarTypeVersionViewModel : SimpleIntegratedViewModel<RepCarTypeVersion>
    {
        #region 私有字段
        /// <summary>
        /// 对应的UserPage引用
        /// </summary>
        private readonly BaseUserControl? _ownerPage;
        #endregion

        #region 按钮状态属性
        /// <summary>
        /// 更新按钮是否启用
        /// </summary>
        public bool UpdateBtnEnabled => CanUpdate(SelectedModel);

        /// <summary>
        /// 删除按钮是否启用
        /// </summary>
        public bool DeleteBtnEnabled => CanDelete(SelectedModel);
        #endregion

        #region 查询条件属性
        private string? _name;
        /// <summary>
        /// 车型版本名称
        /// </summary>
        public string? Name
        {
            get => _name;
            set => SetProperty(ref _name, value);
        }

        private string? _vehicleSeriesId;
        /// <summary>
        /// 车系ID
        /// </summary>
        public string? VehicleSeriesId
        {
            get => _vehicleSeriesId;
            set => SetProperty(ref _vehicleSeriesId, value);
        }

        private bool? _status = true;
        /// <summary>
        /// 状态
        /// </summary>
        public bool? Status
        {
            get => _status;
            set => SetProperty(ref _status, value);
        }
        #endregion

        #region 重写选中，刷新按钮状态方法
        /// <summary>
        /// 重写选中模型改变事件，同时刷新按钮启用状态
        /// </summary>
        protected override void OnSelectedModelChanged()
        {
            base.OnSelectedModelChanged();
            OnPropertyChanged(nameof(UpdateBtnEnabled));
            OnPropertyChanged(nameof(DeleteBtnEnabled));
        }

        /// <summary>
        /// 重写数据改变事件，同时刷新按钮启用状态
        /// </summary>
        protected override void OnDataChanged()
        {
            base.OnDataChanged();
            OnPropertyChanged(nameof(UpdateBtnEnabled));
            OnPropertyChanged(nameof(DeleteBtnEnabled));
        }
        #endregion

        #region 构造函数，加载表格按钮
        public CarTypeVersionViewModel()
        {
            
        }

        public CarTypeVersionViewModel(BaseUserControl ownerPage)
        {
            _ownerPage = ownerPage;
            InitializeButtons();
            // 立即刷新命令状态，确保按钮在页面加载时可用
            Dispatcher.UIThread.Post(() => 
            {
                OnPropertyChanged(nameof(UpdateBtnEnabled));
                OnPropertyChanged(nameof(DeleteBtnEnabled));
            });
            
            _ = Task.Run(async () => await QueryAsync());
        }
        /// <summary>
        /// 初始化表格上方按钮
        /// </summary>
        private void InitializeButtons()
        {
            ButtonItems.Add(new ButtonItem
            {
                Name = "新增",
                InvokeCommand = AddCommand
            });

            ButtonItems.Add(new ButtonItem
            {
                Name = "编辑",
                InvokeCommand = UpdateCommand
            });

            ButtonItems.Add(new ButtonItem
            {
                Name = "批量删除",
                InvokeCommand = BatchDeleteCommand
            });

            ButtonItems.Add(new ButtonItem
            {
                Name = "导入",
                InvokeCommand = ImportCommand
            });

            ButtonItems.Add(new ButtonItem
            {
                Name = "导出",
                InvokeCommand = ExportCommand
            });

            ButtonItems.Add(new ButtonItem
            {
                Name = "导出模板",
                InvokeCommand = ExportTemplateCommand
            });
        }
        #endregion

        #region 实现抽象方法,查询，重置，新增，修改，删除，批量删除

        /// <summary>
        /// 查询数据
        /// </summary>
        public override async Task QueryAsync()
        {
            try
            {
                IsLoading = true;

                // 清空数据
                await Dispatcher.UIThread.InvokeAsync(() =>
                {
                    if (Data == null)
                        Data = new ObservableCollection<RepCarTypeVersion>();
                    else
                        Data.Clear();
                });

                // 调用API
                var res = await HttpHelper<PageModel<RepCarTypeVersion>>.PostAsync(ApiUrl.QueryCarTypeVersionPages, new ReqQueryCarTypeVersionPage()
                {
                    //Name = Name,
                    VehicleSeriesId = VehicleSeriesId,
                    PageSize = PageSize,
                    PageNo = PageNo
                });

                // 处理结果
                if (res.Code == StatusCodeEnum.OK && res.Data != null)
                {
                    await Dispatcher.UIThread.InvokeAsync(() =>
                    {
                        foreach (var item in res.Data.Data)
                        {
                            item.IsSelected = false;
                            Data!.Add(item);
                        }
                    });

                    RefreshPagination(res.Data.TotalCount,res.Data.TotalPage);
                }
                else
                {
                    ShowError(res.Msg ?? "查询失败");
                }
            }
            catch (System.Exception ex)
            {
                ShowError($"查询失败：{ex.Message}");
            }
            finally
            {
                IsLoading = false;
            }
        }

        /// <summary>
        /// 重置
        /// </summary>
        public override void Reset()
        {
            Name = string.Empty;
            VehicleSeriesId = string.Empty;
            Status = true;
            PageNo = 1;
            base.Reset();
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override async Task AddAsync(RepCarTypeVersion? obj = default)
        {
            try
            {
                var res = await Dialog.ShowModal<Page_CarTypeVersion_Modify, CarTypeVersionModifyViewModel>(
                    new CarTypeVersionModifyViewModel(null, ViewStatus.Add),
                    options: GetDialogOptions("新增车型版本"));

                if (res == DialogResult.OK)
                {
                    await QueryAsync();
                }
            }
            catch (System.Exception ex)
            {
                ShowError($"新增失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="obj"></param>
        public override async Task UpdateAsync(RepCarTypeVersion? obj = default)
        {
            var target = obj ?? SelectedModel;
            if (target == null)
            {
                ShowWarning("请选择要修改的车型版本");
                return;
            }

            try
            {
                var res = await Dialog.ShowModal<Page_CarTypeVersion_Modify, CarTypeVersionModifyViewModel>(
                    new CarTypeVersionModifyViewModel(target.Id, ViewStatus.Edit),
                    options: GetDialogOptions("修改车型版本"));

                if (res == DialogResult.OK)
                {
                    await QueryAsync();
                }
            }
            catch (System.Exception ex)
            {
                ShowError($"修改失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="obj"></param>
        public override async Task DeleteAsync(RepCarTypeVersion? obj = default)
        {
            var target = obj ?? SelectedModel;
            if (target == null)
            {
                ShowWarning("请选择要删除的数据");
                return;
            }

            try
            {
                var result = await ShowMsgInfo("确认删除吗", "提示", MessageBoxIcon.Asterisk, MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.OK)
                {
                    var res = await HttpHelper<int>.DeleteAsync($"{ApiUrl.DeleteCarTypeVersion}/{target.Id}");
                    if (res.Code == StatusCodeEnum.OK)
                    {
                        ShowSuccess("删除成功");
                        await QueryAsync();
                    }
                    else
                    {
                        ShowError(res.Msg ?? "删除失败");
                    }
                }
            }
            catch (System.Exception ex)
            {
                ShowError($"删除失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        public override async Task BatchDeleteAsync(IEnumerable<RepCarTypeVersion>? items = null)
        {
            var selectedItems = items?.ToList() ?? GetSelectedItems();
            if (!selectedItems.Any())
            {
                ShowWarning("请选择要删除的数据");
                return;
            }

            try
            {
                var result = await ShowMsgInfo($"确认删除选中的 {selectedItems.Count} 条数据吗？", "提示", MessageBoxIcon.Asterisk, MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.OK)
                {
                    var ids = selectedItems.Select(m => m.Id).ToList();
                    var res = await HttpHelper<int>.DeleteAsync($"{ApiUrl.DeleteCarTypeVersion}/{string.Join(",", ids)}");
                    if (res.Code == StatusCodeEnum.OK)
                    {
                        ShowSuccess("批量删除成功");
                        await QueryAsync();
                    }
                    else
                    {
                        ShowError(res.Msg ?? "批量删除失败");
                    }
                }
            }
            catch (System.Exception ex)
            {
                ShowError($"批量删除失败：{ex.Message}");
            }
        }

        #endregion

        #region 导入导出功能

        /// <summary>
        /// 导入
        /// </summary>
        protected override async Task ImportAsync()
        {
            try
            {
                var res = await Dialog.ShowModal<ImportPage, ImportViewModel>(
                    new ImportViewModel(_ownerPage, null, ViewStatus.Add, ImportType.CarTypeVersion),
                    options: GetDialogOptions("导入车型版本数据"));

                if (res == DialogResult.OK)
                {
                    await QueryAsync();
                }
            }
            catch (System.Exception ex)
            {
                ShowError($"导入失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        protected override async Task ExportAsync()
        {
            try
            {
                var desktop = Application.Current?.ApplicationLifetime as Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime;
                var topLevel = desktop?.MainWindow;
                if (topLevel == null) return;

                var file = await topLevel.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
                {
                    Title = "导出车型版本数据",
                    DefaultExtension = "csv",
                    SuggestedFileName = $"车型版本数据_{DateTime.Now:yyyyMMddHHmmss}.csv",
                    FileTypeChoices = new[] { FilePickerFileTypes.All }
                });

                if (file != null)
                {
                    var filePath = file.Path.LocalPath;

                    // 获取选中的数据
                    var selectedItems = GetSelectedItems();

                    ReqExportCarTypeVersion requestData;
                    if (selectedItems.Any())
                    {
                        // 如果有选中数据，导出选中的数据
                        var selectedIds = selectedItems.Select(x => x.Id).ToList();
                        requestData = new ReqExportCarTypeVersion
                        {
                            Ids = selectedIds,
                            ExportType = EnumExportType.Selected
                        };
                    }
                    else
                    {
                        // 如果没有选中数据，使用查询条件导出所有数据
                        requestData = new ReqExportCarTypeVersion
                        { 
                            VehicleSeriesId = VehicleSeriesId,
                            ExportType = EnumExportType.All
                        };
                    }

                    var res = await HttpHelper<byte[]>.PostAsync(ApiUrl.ExportCarTypeVersion, requestData);

                    if (res.Code == StatusCodeEnum.OK && res.Data != null)
                    {
                        await File.WriteAllBytesAsync(filePath, res.Data);
                       var exportStr = selectedItems.Any() ? $"共导出{selectedItems.Count()}条数据" : "所有";
                        ShowSuccess($"导出成功，{exportStr}");
                    }
                    else
                    {
                        ShowError(res.Msg ?? "导出失败");
                    }
                }
            }
            catch (System.Exception ex)
            {
                ShowError($"导出失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 导出模板
        /// </summary>
        protected override async Task ExportTemplateAsync()
        {
            try
            {
                var desktop = Application.Current?.ApplicationLifetime as Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime;
                var topLevel = desktop?.MainWindow;
                if (topLevel == null) return;

                var file = await topLevel.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
                {
                    Title = "导出车型版本数据模板",
                    DefaultExtension = "csv",
                    SuggestedFileName = $"车型版本数据模板_{DateTime.Now:yyyyMMddHHmmss}.csv",
                    FileTypeChoices = new[] { FilePickerFileTypes.All }
                });

                if (file != null)
                {
                    var filePath = file.Path.LocalPath;
                    var res = await HttpHelper<byte[]>.GetAsync(ApiUrl.ExportCarTypeVersionTemplate);

                    if (res.Code == StatusCodeEnum.OK && res.Data != null)
                    {
                        await File.WriteAllBytesAsync(filePath, res.Data);
                        ShowSuccess("模板导出成功");
                    }
                    else
                    {
                        ShowError(res.Msg ?? "模板导出失败");
                    }
                }
            }
            catch (System.Exception ex)
            {
                ShowError($"模板导出失败：{ex.Message}");
            }
        }
        #endregion

        #region 选择状态管理

        /// <summary>
        /// 获取项目的选中状态
        /// </summary>
        /// <param name="item">项目</param>
        /// <returns>是否选中</returns>
        protected override bool GetIsSelected(RepCarTypeVersion item)
        {
            return item.IsSelected;
        }

        /// <summary>
        /// 设置项目的选中状态
        /// </summary>
        /// <param name="item">项目</param>
        /// <param name="isSelected">是否选中</param>
        protected override void SetIsSelected(RepCarTypeVersion item, bool isSelected)
        {
            item.IsSelected = isSelected;
        }

        #endregion
    }
}